<template>
  <div class="main">
    <div class="air-column">
      <h2>剩机人</h2>
      <el-form class="member-info" :model="{users}" ref="UsersForm">
        <div class="member-info-item" v-for="(users,index) in users" :key="index">
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[
                   { required: true, message: '请输入乘机人', trigger: 'blur' }
                    ]"
          >
            <el-input placeholder="姓名" class="input-with-select" v-model="users.username">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
                   { required: true, message: '请输入证件号码', trigger: 'blur' }
                    ]"
          >
            <el-input placeholder="证件号码" class="input-with-select" v-model="users.id">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <div class="insurance-item" v-for="item in selectAir.insurances" :key="item.id">
          <el-checkbox-group v-model="insurancesList">
            <!-- checkbox-group元素能把多个 checkbox 管理为一组，只需要在 Group 中使用v-model绑定Array类型的变量即可。 -->
            <!-- label属性是该 checkbox 对应的值 ,若该标签中无内容，则该属性也充当 checkbox 按钮后的介绍-->
            <el-checkbox
              :label="item.id"
              border
            >{{`${item.type}：￥${item.price}/份×1 最高赔付${item.compensation}`}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="60px"
          :model="{contactName,contactPhone,captcha}"
          :rules="rules"
          ref="ContactForm"
        >
          <el-form-item label="姓名" prop="contactName" class="aaaa">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone" class="aaaa">
            <el-input placeholder="请输入内容" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha" class="aaaa">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="warning" class="submit" @click="handleSubmit">提交订单</el-button>
      </div>

      <!-- 登录注册功能组件 -->
      <transition name="el-fade-in-linear">
        <div v-show="show" class="location">
          <!-- 表单头部tab -->
          <el-row type="flex" justify="center" class="tabs">
            <span
              :class="{active: currentTab === index}"
              v-for="(item, index) in [`登录`, `注册`]"
              :key="index"
              @click="handleChangeTab(index)"
            >{{item}}</span>
          </el-row>

          <!-- 登录功能组件 -->
          <LoginForm v-if="currentTab == 0" />

          <!-- 注册功能组件 -->
          <RegisterForm v-if="currentTab == 1" @tologin="currentTab = 0" />
        </div>
      </transition>
      <!-- </div> -->
    </div>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";
import RegisterForm from "@/components/user/RegisterForm";
export default {
  props: {
    selectAir: Object,
  },
  components: {
    LoginForm,
    RegisterForm,
  },
  data() {
    return {
      sun: 0,
      show: false,
      currentTab: 0,

      users: [
        // 原始数据只有一个乘机人
        {
          username: "",
          id: "",
        },
      ],

      // 保险选项数据
      insurancesList: [],
      contactName: "",
      contactPhone: "",
      captcha: "",
      invoice: false,

      rules: {
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
    };
  },

  //监听
  watch: {
    users: {
      handler() {
        this.calcTotalPrice();
      },
      immediate: true,
    },

    insurancesList: {
      handler() {
        this.calcTotalPrice();
      },
      immediate: true,
    },

    "$store.state.user.userInfo.token": function () {
      if (!this.$store.state.user.userInfo.token) {
        this.show = true;
      } else {
        setTimeout(() => {
          this.show = false;
        }, 1500);
      }
    },
  },

  methods: {
    //计算总价函数
    calcTotalPrice() {
      var sun = 0;
      sun += this.selectAir.seat_infos.org_settle_price * this.users.length;
      this.selectAir.insurances.forEach((element) => {
        // 遍历保险, 如果发现id存在于被选中的列表中, 就要乘以乘机人数量, 添加到结果中
        if (this.insurancesList.indexOf(element.id) >= 0) {
          //查找值在数组中第一次出现的下标,0也是下标
          sun += element.price * this.users.length;
        }
      });
      this.sun = sun;
      this.$emit("suns", this.sun);
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: "",
      });
    },
    handleChangeTab(index) {
      this.currentTab = index;
    },
    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      if (!this.contactPhone) {
        this.$message.error("请先输入手机号");
        return;
      }
      this.$axios({
        method: "post",
        url: "/captchas",
        data: {
          tel: this.contactPhone,
        },
      }).then((res) => {
        console.log(res);
        if (res.data.code == "000000") {
          this.$message.success("临时验证码:000000");
        }
      });
    },

    // 提交订单
    async handleSubmit() {
      if (!this.$store.state.user.userInfo.token) {
        this.show = true;
        return this.$message("请先登陆!");
      }
      var isVaildUsersForm = await this.$refs.UsersForm.validate().catch(
        (e) => {}
      );
      var isVaildVontactForm = await this.$refs.ContactForm.validate().catch(
        (e) => {}
      );

      if (isVaildUsersForm && isVaildVontactForm) {
        console.log(this.users);
        let data = {
          users: this.users,
          insurances: this.insurancesList,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: this.invoice,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id,
          captcha: this.captcha,
        };
        console.log(data);
        this.$axios({
          url: "/airorders",
          method: "post",
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token,
          },
          data: data,
        }).then((res) => {
          console.log(res);
          this.$router.push("/air/pay?id=" + res.data.data.id);
        });
      }
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}

.main {
  // width: 1000px;
  height: 100%;
  margin: 0 auto;
  position: relative;
}

.form-wrapper {
  width: 400px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tabs {
  span {
    display: block;
    width: 50%;
    height: 50px;
    box-sizing: border-box;
    border-top: 2px #eee solid;
    background: #eee;
    line-height: 48px;
    text-align: center;
    cursor: pointer;
    color: #666;

    &.active {
      color: orange;
      border-top-color: orange;
      background: #fff;
      font-weight: bold;
    }
  }
}

/deep/ .el-form-item__label {
  padding: 0;
  margin-right: 10px;
  line-height: 47px;
}
/deep/ .el-form-item__error {
  position: static;
}
.location {
  width: 400px;
  position: relative;
  left: 600px;
  top: -500px;
  border: 2px solid #f5f7fa;
}
</style>
